var inst1;
var tree;
var transfer;
var pageSize = 10;
var toPage;
var group;
var selectedNode = null;
$('#page').paging({
    pageNo: 0,
    totalPage: 0,
    totalSize: 0,
    showJump: true,
    callback: function (num) {
        //加载
    },
    showSizeChange: true,
    sizeList: [10, 15, 20],
    pageSize: pageSize,
    sizeChangeFun: function (size) {
        pageSize = size;
        //加载
    }
});

$(function () {
    addGroupValidation();
    loadTree();
    loadTransfer();//穿梭框初始化
    loadDefaultGroup();
});

/*添加设备分组*/
function addGroup() {
    //重置表单、表单验证
    $("#addGroupForm")[0].reset();
    $('#groupID').val('');
    transfer.reload('transfer1', {
        value: []
    });
    $("#addGroupForm").data('bootstrapValidator').destroy();
    addGroupValidation();
    $('#addGroupModal').modal();
    $('#modal_title').text('新建分组');
}

$('#addGroupModal').on('shown.bs.modal', function () {
    transfer.reload('transfer1', {
        showSearch: true
    });
});

/*给分组添加生产设备*/
function addDevice() {
    $('#addDeviceModal').modal();
    tree.reload('tree2');
    tree.setChecked('tree2', selectedNode);
}

/*删除分组中的设备*/
function deleteDevice(id) {
    myConfirm('删除确认', '生产设备删除后，该分组权限下人员将无法看到该设备信息，是否确认删除？', function (res) {
        if (res) {
            getJson("/deviceGroup/deleteGroupDevice", {group: group, device: id}, 'GET', function (result) {
                if (result['code'] == 200) {
                    myAlert('删除提示', '删除成功');
                    loadDeviceList(toPage);
                    return;
                }
                myAlert('删除提示', '删除失败');
            })
        }
    })
}

/*加载树*/
function loadTree() {
    layui.use('tree', function () {
        tree = layui.tree;
        getJson("/deviceGroup/getGroupList", null, 'GET', function (result) {
            let dataArray = new Array();
            for (let item of result['payload']['data']) {
                dataArray.push({title: item['name'], id: item['id']});
            }
            let edit = new Array();
            if (enterpriseGroupPoera) {
                edit.push('update');
                edit.push('del');
            }
            inst1 = tree.render({
                elem: '#groupListTree',
                edit: edit,
                onlyIconControl: true,//仅允许节点左侧图标控制展开收缩
                id: 'tree1',
                data: dataArray,
                click: function (obj) {
                    let id = obj.data.id;
                    group = id;
                    loadDeviceList();
                    loadGroupInfo(id);
                },
                customOperate: true,
                operate: function (obj) {
                    var type = obj.type; //操作类型：edit、del
                    var data = obj.data; //当前节点数据
                    //Ajax 操作
                    var id = data.id; //节点索引
                    if (type === 'update') { //修改
                        //重置表单、表单验证
                        $("#addGroupForm")[0].reset();
                        transfer.reload('transfer1', {
                            value: []
                        });
                        $("#addGroupForm").data('bootstrapValidator').destroy();

                        $('#modal_title').text('编辑分组');
                        $('#groupID').val(id);
                        addGroupValidation();
                        loadUpdateGroupInfo(id);
                    } else if (type === 'del') { //删除节点
                        myConfirm('操作确认', '分组删除后，若该分组下人员无其他分组权限，将展示所有设备数据权限，是否继续删除？', function (res) {
                            if (res) {
                                //删除
                                getJson("/deviceGroup/deleteDeviceGroup", {group: id}, 'GET', function (result) {
                                    if (result['code'] == 200) {
                                        myAlert("提示", "删除成功", function () {
                                            location.reload();
                                        });
                                    } else {
                                        myAlert("提示", result['message']);
                                    }
                                })
                            }
                        });
                    }
                }
            });
        })
        tree.render(
            getJson(path, null, 'GET', function (result) {
                if (result['code'] == 200) {
                    let data = buildTree(result['payload']['data'], path);
                    getJson("/deviceType/getNoTypeDevice", null, 'GET', function (list) {
                        if (list['code'] == 200 && list['payload']['data'].length > 0) {
                            data.push({
                                id: 0,
                                rank: 0,
                                spread: true,
                                title: '其它',
                                children: [{id: 0, rank: 0, spread: true, title: '无类型设备',}]
                            });
                        }
                        tree = layui.tree;
                        //渲染
                        inst1 = tree.render({
                            elem: '#deviceListTree',
                            id: 'tree2',
                            showCheckbox: true,
                            data: data,
                            click: function (obj) {
                            },
                        })
                    })
                }
                hideLoading();
            })
        )
    });
}

/*添加生产设备保存操作*/
function submitDevice() {
    showLoading("数据提交中")
    let checkedData = tree.getChecked('tree2'); //获取选中节点的数据
    getJson("/deviceGroup/addGroupDevice", {
        data: JSON.stringify(checkedData),
        group: group
    }, 'POST', function (result) {
        hideLoading();
        if (result['code'] == 200) {
            myAlert('提示', '添加成功', function () {
                // loadDeviceList(toPage);
                window.location.reload();
                $('#addDeviceModal').modal('hide');
                return;
            });
        }
        myAlert('提示', result['message']);
    })
}

/* 加载穿梭框 */
function loadTransfer() {
    layui.use('transfer', function () {
        getJson("/sys/user/getUserByAreas", null, 'GET', function (result) {
            let dataArray = new Array();
            for (let item of result['payload']['data']) {
                if (item['createBy'] != 1) {
                    dataArray.push({"value": item['id'], "title": item['displayName'], "disabled": "", "checked": ""});
                } else {
                    dataArray.push({
                        "value": item['id'],
                        "title": item['displayName'],
                        "disabled": true,
                        "checked": ""
                    });
                }
            }
            transfer = layui.transfer;
            transfer.render({
                elem: '#transfer',
                title: ['人员列表', '已选择人员'],
                showSearch: true,
                data: dataArray,
                value: [],//所选人员，与data中的value值对应
                id: 'transfer1' //索引
            });
        })
    });
}

/*添加设备分组表单验证*/
function addGroupValidation() {
    $('#addGroupForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    notEmpty: {}
                }
            },
            desc: {
                validators: {
                    stringLength: {
                        min: 0,
                        max: 50
                    }
                }
            },
        }
    }).on('success.form.bv', function (e) {
        e.preventDefault();//防止表单提交
        showLoading('数据提交中');
        let formData = JSON.stringify({
            id: $('#groupID').val(),
            name: $('#validationCustom01').val(),
            desc: $('#validationCustom02').val(),
            userList: transfer.getData('transfer1')
        });
        $.ajax({
            url: host + "/deviceGroup/saveOrUpdateDeviceGroup",
            type: 'post',
            data: formData,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            beforeSend: function (xhr) {
                xhr.setRequestHeader('token', sessionStorage.getItem("token"));
            },
            success: function (result) {
                hideLoading();
                if (result['code'] == 200) {
                    myAlert('提示', '保存成功', function () {
                        loadTree();
                        loadDefaultGroup();
                        $('#addGroupModal').modal('hide');
                        return;
                    });
                }
                myAlert('提示', '保存失败');
            }
        })
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('#addGroupForm [type="submit"]').removeAttr("disabled");
    });
}

/*获取设备分组详情*/
function loadGroupInfo(id) {
    selectedNode = null;
    getJson("/deviceGroup/getOneById", {id: id}, 'GET', function (result) {
        if (!isNull(result['desc'])) {
            $('#groupDesc').text(result['desc']);
        } else {
            $('#groupDesc').text('暂无描述');
        }
        if (!isNull(result['userList'])) {
            let userList = '';
            for (let item of result['userList']) {
                userList += item['title'] + '、';
            }
            if (!isNull(userList)) {
                $('#groupUserList').text(userList.substr(0, userList.length - 1));
            } else {
                $('#groupUserList').text('暂未有人员分配至该分组权限！');
            }
        } else {
            $('#groupUserList').text('暂未有人员分配至该分组权限！');
        }
        if (!isNull(result['selectedNode'])) {
            selectedNode = result['selectedNode'].split(',');
        }
    })
}

/*点击修改时获取分组详细，加载以选择用户列表*/
function loadUpdateGroupInfo(id) {
    showLoading(LOADING);
    getJson("/deviceGroup/getOneById", {id: id}, 'GET', function (data) {
        tree.setChecked('tree2', data['selectedNode'])
        $('#validationCustom01').val(data['name']);
        $('#validationCustom02').val(data['desc']);
        let userArray = [];
        if (!isNull(data['userList'])) {
            for (let item of data['userList']) {
                userArray.push(item['value']);
            }
        }
        transfer.reload('transfer1', {
            value: userArray
        });
        $('#addGroupModal').modal();
        hideLoading();
    })
}

/*加载设备列表*/
function loadDeviceList(_pageIndex) {
    showLoading(LOADING);
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    getJson("/deviceGroup/getDeviceListByGroup", {
        id: group,
        param: $('#searchValue').val(),
        pageIndex: pageIndex,
        pageSize: pageSize
    }, 'GET', function (result) {
        if (result['code'] == 200) {
            let data = result['payload']['data'];
            setPage($('#page'), pageIndex, result['payload']['pages'], result['payload']['total'], function (num) {
                loadDeviceList(num);
            });
            let order = 1 + 10 * (pageIndex - 1);
            for (let item of data) {
                item['order'] = order++;
            }
            buildTable($('#deviceList'), title, label, data, function (td, label, item) {
                switch (label) {
                    case 'opera':
                        let edit = createElement('a', td);
                        $(edit).addClass('delete-option-btn');
                        $(edit).attr('href', '##');
                        $(edit).text('删除');
                        $(edit).click(function () {
                            deleteDevice(item['id']);
                        });
                        break;
                }
            })
            hideLoading();
        }
    })
}

/*加载默认分组*/
function loadDefaultGroup() {
    getJson("/deviceGroup/getGroupList", null, 'GET', function (result) {
        if (!isNull(result['payload']['data']) && result['payload']['data'].length > 0) {
            group = result['payload']['data'][0]['id'];
            //loadGroupInfo(group);
            loadDeviceList();
            loadGroupInfo(group);
        }
    })
}